<template>
  <div class="monitor-tree-root" :style="{
    'height': fixedBox.height,
    'width': fixedBox.width
  }">
    <controlPanel v-if="showSetting" :online-count="monitor.onlineCount" :warn-clount="monitor.warnCount"
      :offline-count="monitor.offlineCount" @click-refresh="getMonitorAppsTree">
    </controlPanel>

    <div class="monitor-tree" ref="MonitorChartRef" v-loading="monitor.loading" element-loading-text="正在查询集群列表, 请稍后...">
    </div>
  </div>
</template>

<script setup lang="ts">
import * as echartTheme from '@/assets/styles/xz/echartTheme';
import { ref, shallowRef, onUnmounted, onMounted, onActivated, inject } from "vue";
import { monitorAppsTreeApi } from '@/api/guardcat';
import { isNull, isNotNull } from "@/assets/utils/obj";
import controlPanel from './ControlPanel.vue';
// echarts
import * as echarts from 'echarts/core';
import { GridComponent, TitleComponent, TooltipComponent } from 'echarts/components';
import { EffectScatterChart, ScatterChart, TreeChart } from 'echarts/charts';
import { UniversalTransition } from 'echarts/features';
import { CanvasRenderer } from 'echarts/renderers';

echarts.use([UniversalTransition, TitleComponent, TooltipComponent, GridComponent, TreeChart, EffectScatterChart, ScatterChart, CanvasRenderer]);


// -------------------- inject
const fixedBox: any = inject('monitorTreeFixedBox', { height: '100%', width: '100%' });

// -------------------- props
const props = defineProps({
  showSetting: { tyle: Boolean, default: true },
  showTooltip: { tyle: Boolean, default: true },
  width: {}
})

// -------------------- data
const MonitorChartRef = ref<any>(null)
const monitorChart = shallowRef<any>(null);
const monitor = ref({
  loading: true,
  data: [{}],
  onlineCount: 0,
  warnCount: 0,
  offlineCount: 0,
});

// -------------------- methods
const getMonitorAppsTree = (callback?: any) => {
  monitor.value.loading = true;
  monitorAppsTreeApi().then(resp => {
    let data: any = resp.data;
    for (let i = 0; i < data.length; i++) {
      if (isNull(data[i].children)) {
        continue;
      }
      for (let j = 0; j < data[i].children.length; j++) {
        if (data[i].children[j].status === 'OFFLINE') {
          data[i].children[j]['itemStyle'] = echartTheme.treemap().failItemStyle;
          data[i].children[j]['lineStyle'] = echartTheme.treemap().failLineStyle;
          data[i]['lineStyle'] = echartTheme.treemap().warnLineStyle;
        } else {
          if (data[i].children[j].status === 'ONLINE') {
            data[i].children[j]['itemStyle'] = echartTheme.treemap().succItemStyle;
            data[i].children[j]['lineStyle'] = echartTheme.treemap().succLineStyle;
          }
          if (data[i].children[j].alertCount > 0) {
            data[i].children[j]['itemStyle'] = echartTheme.treemap().warnItemStyle;
            data[i].children[j]['lineStyle'] = echartTheme.treemap().warnLineStyle;
            data[i]['lineStyle'] = echartTheme.treemap().warnLineStyle;
          }
        }

      }
      monitor.value.data = [{ name: 'Spring\nBoot ', appType: 'root', children: data }];
      renderChart();
    }

    if (isNotNull(callback)) {
      callback();
    }

    setTimeout(() => {
      monitor.value.loading = false;
    }, 500);

    setTimeout(() => {
      let onlineMachineCount = 0, warnMachineCount = 0, offlineMachineCount = 0;
      for (let i = 0; i < data.length; i++) {
        for (let j = 0; j < data[i].children.length; j++) {
          if (data[i].children[j].status === 'OFFLINE') {
            offlineMachineCount++;
          } else if (data[i].children[j].alertCount > 0) {
            warnMachineCount++;
          } else {
            onlineMachineCount++;
          }
        }
      }
      monitor.value.onlineCount = onlineMachineCount;
      monitor.value.warnCount = warnMachineCount;
      monitor.value.offlineCount = offlineMachineCount;
    }, 0);
  });
};

const renderChart = () => {
  monitorChart.value.setOption({
    title: {
      top: 5, right: 5, text: '集群节点树',
      textStyle: { fontSize: 14, color: echartTheme.common().titleColor }
    },
    tooltip: {
      trigger: 'item',
      triggerOn: 'click',// mousemove|click
      enterable: true, // 鼠标可进入悬浮窗
      confine: true,
      padding: 0,
      borderWidth: 0,
      // alwaysShowContent: true,
      hideDelay: 50000,
      backgroundColor: 'rgba(0,0,0,0)',
      extraCssText: 'box-shadow: 0 0 3px rgba(0, 0, 0, 0);',
      position: (pos: any, params: any, el: any, elRect: any, size: any) => {
        return { top: 30, left: 30 };
      }
    },
    grid: { top: 0, right: 0, left: 0, bottom: 0 },
    xAxis: {
      type: 'value', min: 0, max: 10, interval: 1,
      axisLine: { lineStyle: { color: echartTheme.treemap().axisLineColor } },
      splitLine: { lineStyle: { color: echartTheme.treemap().axisLineColor } },
    },
    yAxis: {
      type: 'value', min: 0, max: 10, interval: 1,
      axisLine: { lineStyle: { color: echartTheme.treemap().axisLineColor } },
      splitLine: { lineStyle: { color: echartTheme.treemap().axisLineColor } },
    },
    series: [
      {
        type: 'tree', z: 10,
        top: '1%', right: '40%', bottom: '1%', left: '10%',
        symbol: 'roundRect',
        symbolSize: 13,
        edgeForkPosition: '100%', // 折线中曲折的位置
        expandAndCollapse: true,  // 是否允许展开合并节点
        label: {
          fontSize: 13,
          fontFamily: 'JetBrains Mono, Consolas, Monaco',
          color: echartTheme.common().textColor,
          position: 'left',
          verticalAlign: 'middle',
          align: 'right',
          padding: [0, 5]
        },
        leaves: { label: { position: 'right', verticalAlign: 'middle', align: 'left' } },
        itemStyle: {
          color: '#95d977',
          borderColor: '#538c37',
          shadowColor: 'rgba(0, 0, 0, 0.3)',
          shadowBlur: 5,
          shadowOffsetX: 3,
          shadowOffsetY: 3,
        },
        lineStyle: {
          width: 1,
          color: '#d2d2d2',
          shadowColor: 'rgba(0, 0, 0, 0.3)',
          shadowBlur: 10,
          shadowOffsetX: 3,
          shadowOffsetY: 3,
        },
        data: monitor.value.data,
        emphasis: {
          focus: 'relative'
        }
      }
    ]
  })
}

const init = () => {
  monitorChart.value = echarts.init(MonitorChartRef.value);
}

const windowResize = () => {
  monitorChart.value.resize();
  window.onresize = function () {
    monitorChart.value.resize();
  }
}

onMounted(() => {
  init();
  windowResize();
  getMonitorAppsTree();
})

onActivated(() => {
  windowResize();
})

onUnmounted(() => {
})

defineExpose({
  getMonitorAppsTree, windowResize
})
</script>

<style scoped lang="scss">
.monitor-tree-root {
  @include flex(column, flex-start, center);
  position: relative;
  overflow: hidden;

  .monitor-tree {
    @include box(100%, 100%);
  }
}
</style>

<style>
.monitor-tree-toolip-root {
  border-radius: 10px;
  background-color: rgba(255, 255, 255, 0.1);
}
</style>
